﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.IO;
using UnityEngine;

namespace DashFire
{
  internal class DownLoaderManager
  {
    #region 单例
    public static DownLoaderManager Instance { get { return sInstance; } }
    private static DownLoaderManager sInstance = new DownLoaderManager();
    private DownLoaderManager() { }
    #endregion

    public void StartDownLoad(List<string> FileList)
    {
      mFileList = FileList;
      ResUpdateMessage.Instance.Log("StartDownLoad");
      CoroutineProxy.Instance.StartCoroutine(DownCoroutine());
    }

    IEnumerator DownCoroutine()
    {
      mDownLoadUrlQueue.Clear();
      foreach (var file in mFileList)
      {
        mDownLoadUrlQueue.Enqueue(file + ".7z");
      }

      ClientConcurrentQueue<string> decompressQueue
        = new ClientConcurrentQueue<string>();  //解压队列

      while (mDownLoadUrlQueue.Count > 0 || decompressQueue.Count > 0)
      {
        string url = string.Empty;
        if(mDownLoadUrlQueue.TryDequeue(out url)  )
        {
          ResUpdateMessage.Instance.SendDownLoadMessage(url);
          ResUpdateMessage.Instance.Log("Donw Load File : {0}", url);
          mDownLoader.DownLoad(GetDownLoadUrl(url), GetLocalPath(url), null);
        }

        if (decompressQueue.Count > 0)
        {
          string dUrl = string.Empty;
          if(decompressQueue.TryDequeue(out dUrl))
          {
            Decompress(dUrl);
          }
        }

        if(url != string.Empty)
        {
          while (mDownLoader.IsDone() == false)
          {
            yield return null;
          }

          if(mDownLoader.Error == null)
          {
            decompressQueue.Enqueue(url);
          }
          else
          {

          }
          
        }

        yield return null;
      }
    }

    private void Decompress(string url)
    {
      string source = GetLocalPath(url);
      if(ResUpdateChecker.Instance.HashVerify(source) == false)
      {
        //Hash码校验失败重新下载
        ResUpdateMessage.Instance.Log("Hash Verify Failed , {0}", url);
        mDownLoadUrlQueue.Enqueue(url); 
        return;
      }

      ResUpdateMessage.Instance.DeCompressMessage(url);
      ResUpdateMessage.Instance.Log("Decompress File {0}", url);

      int index = source.LastIndexOf('.');
      string target = source.Substring(0, index);
      string err = FileCompress.Decompress(source, target);
      if(string.IsNullOrEmpty(err))
      { 
        //解压成功
        FileInfo fi = new FileInfo(source);
        fi.Delete();
        ResUpdateChecker.Instance.SaveLocalHash(source);
      }
      else
      {
        Debug.Log(err);
      }


    }
    private void PushQueue(Queue<string> q, string v)
    {
      lock(q)
      {
        q.Enqueue(v);
      }
    }
    private string GetDownLoadUrl(string file)
    {
      return URL + file;
    }

    private string GetLocalPath(string RelativePath)
    {
      return Application.persistentDataPath + "/" + RelativePath;
    }

    public string URL { get; set; }

    List<string> mFileList = null;

    HttpDownLoader mDownLoader = new HttpDownLoader();

    ClientConcurrentQueue<string> mDownLoadUrlQueue
      = new ClientConcurrentQueue<string>();  //下载队列
  }
}
